import React, { useEffect, useState } from 'react';
import { Button, Modal, Table, Tag, Transfer, message } from 'antd';
import type { TableColumnsType, TableProps, TransferProps } from 'antd';
import { TransferItem } from 'antd/es/transfer';
const _ = require('lodash');
import { useIntl } from '@umijs/max';
type TableRowSelection<T extends object> = TableProps<T>['rowSelection'];


interface DataType {
    key: string;
    title: string;
    description: string;
    tag: string;
}

interface TableTransferProps extends TransferProps<TransferItem> {
    dataSource: DataType[];
    leftColumns: TableColumnsType<DataType>;
    rightColumns: TableColumnsType<DataType>;
}

// Customize Table Transfer
const TableTransfer = ({ leftColumns, rightColumns, ...restProps }: TableTransferProps) => (




    <Transfer {...restProps}>
        {({
            direction,
            filteredItems,
            onItemSelect,
            onItemSelectAll,
            selectedKeys: listSelectedKeys,
            disabled: listDisabled,
        }) => {
            const columns = direction === 'left' ? leftColumns : rightColumns;

            const rowSelection: TableRowSelection<TransferItem> = {
                getCheckboxProps: () => ({ disabled: listDisabled }),
                onChange(selectedRowKeys) {
                    onItemSelectAll(selectedRowKeys, 'replace');
                },
                selectedRowKeys: listSelectedKeys,
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE],
            };

            return (
                <Table
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={filteredItems}
                    size="small"
                    style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                    onRow={({ key, disabled: itemDisabled }) => ({
                        onClick: () => {
                            if (itemDisabled || listDisabled) {
                                return;
                            }
                            onItemSelect(key, !listSelectedKeys.includes(key));
                        },
                    })}
                />
            );
        }}
    </Transfer>
);




interface Poprs {
    WhillCheckInflag: boolean
    setWhillCheckInflag: (Event: boolean) => void
    list2: RoomList[]
    dataSource: RoomList[]
    setdataSource: any
}

const userModel: React.FC<Poprs> = ({ dataSource, setdataSource, list2, WhillCheckInflag, setWhillCheckInflag }) => {
    const [dataList, setdataList] = useState([])
    const intl = useIntl()

    const columns: TableColumnsType<DataType> = [
        {
            dataIndex: 'bName',
            title: intl.formatMessage({ id: "business.Building" }),
        },

        {
            dataIndex: 'floor',
            title: intl.formatMessage({ id: "business.floor" }),
            render: (floor: string) => (
                <Tag style={{ marginInlineEnd: 0 }} color="cyan">
                    {/* {"第" + floor + "层"} */}
                    {intl.formatMessage(
                        { id: "business.The layer" },
                        { itemLayer: floor }
                    )}
                </Tag>
            ),
        },
        {
            dataIndex: 'roomName',
            title: intl.formatMessage({ id: "business.Room name" }),
        },
        {
            dataIndex: 'tName',
            title: intl.formatMessage({ id: "business.Room type" }),
        },

    ];


    useEffect(() => {
        // 继续添加房间 如果房间已被添加 那么久不显示已经被添加过的房间 
        if (dataSource.length) {
            const idsToFilter = new Set(dataSource.map(item => item.id));
            let arr = list2 = list2.filter(item => !idsToFilter.has(item.id));
            setdataList(arr)

        } else {
            // 第一次添加房间 不显示被占用和维修的房间
            let arr = list2.filter((item) => {
                return (item.status != '3' && item.status != '4')
            })
            setdataList(arr)
        }

    }, [])

    const Close = () => {
        setWhillCheckInflag(false)
    }
    // 被选中的数据
    const [targetKeys, setTargetKeys] = useState([]);
    const onChange = (nextTargetKeys: React.SetStateAction<never[]>) => {
        setTargetKeys(nextTargetKeys);
    };
    const YesAdd = () => {
        if (!targetKeys.length) return message.error(intl.formatMessage({ id: "business.Please choose a room." }))
        let arr: any[] = []
        targetKeys.forEach((item) => {
            let b = list2.find((l) => {
                if (l.roomId == item) {
                    return l
                }
            })
            arr.push({ ...b, floor: "第" + b.floor + "层" })
        })
        // let arr2 

        const sortedItems = _.sortBy(arr, 'roomName');
        setdataSource((prevDataSource: string) => [...prevDataSource, ...sortedItems]);
        Close()
    }

    return (
        <Modal
            title={intl.formatMessage({ id: "business.Choose the room to add" })}
            open={WhillCheckInflag}
            onCancel={Close}
            width={1100}
            footer={null}
            maskClosable={false}
        >    <>
                <p> </p>
                <TableTransfer
                    dataSource={dataList}
                    targetKeys={targetKeys}
                    showSearch
                    showSelectAll={false}
                    onChange={onChange}
                    filterOption={(inputValue, item) =>
                        item.roomName!.indexOf(inputValue) !== -1 || item.roomName.indexOf(inputValue) !== -1
                    }
                    leftColumns={columns}
                    rightColumns={columns}
                    rowKey={(row) => row.roomId}
                />
            </>
            <br />
            <Button style={{ marginLeft: 965 }} onClick={YesAdd} type='primary'>{intl.formatMessage({ id: "business.Add" })}</Button>
        </Modal>

    );
}

export default userModel